from django.shortcuts import render, redirect
from no_5.models import Administrator

mySalt = "d8s#wc%0t7"  # 可以用默认的


# Create your views here.
# 自定义登录函数视图
def cookieLogin(request):
    message = ""
    if request.method == "POST":
        user = request.POST.get('user')
        pwd = request.POST.get('pwd')
        c = Administrator.objects.filter(username=user, password=pwd).count()
        if c:
            rep = redirect('index.html')
            # rep.set_cookie('username', user)
            # rep.set_cookie('password', pwd)
            # 加密（signed_cookie 只是加了签名的 cookie, 而不是被加密的 cookie, 作用是防止用户私自纂改）
            rep.set_signed_cookie('username', user, salt=mySalt)
            rep.set_signed_cookie('password', pwd, salt=mySalt)
            return rep
        else:
            message = "用户名或密码错误"
    return render(request, 'no_5/pages/cookie/login.html', {'msg': message})


# 访问首页视图函数
def cookieIndex(request):
    # 如果用户已经登录，获取当前登录的用户名
    # 否则，返回登录页面
    # username = request.COOKIES.get('username')
    # password = request.COOKIES.get('password')
    username = request.get_signed_cookie('username', False, salt=mySalt)
    password = request.get_signed_cookie('password', False, salt=mySalt)

    if not username or not password:
        return redirect('/no_5/cookie/login.html')

    c = Administrator.objects.filter(username=username, password=password).count()
    if not c:
        return redirect('/no_5/cookie/login.html')

    return render(request, 'no_5/pages/cookie/index.html', {'username': username})

